#include "label.h"

#include <assert.h>
#include <stdlib.h>
#include <string.h>

void Label_OnInit(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_LABEL);
    STLabel *label = (STLabel *)wnd;
    label->text = NULL;
    DEBUG_LOG("Label_OnInit");
}

void Label_OnDestroy(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_LABEL);
    STLabel *label = (STLabel *)wnd;
    free(label->text);
    DEBUG_LOG("Label_OnDestroy");
}

void Label_OnPaint(STWnd *wnd)
{
    assert(wnd->type == WND_TYPE_LABEL);
    STLabel *label = (STLabel *)wnd;
    DEBUG_LOG("Label_OnPaint text: %s", label->text ? label->text : "NULL text");
}

void Label_SetText(STWnd* wnd, const char* text) {
    assert(wnd->type == WND_TYPE_LABEL);
    STLabel* label = (STLabel*)wnd;
    const STWndVApi* vtbl = (const STWndVApi*)wnd->vApi;
    
    free(label->text);
    label->text = strdup(text);
    
    // 触发重绘
    if (vtbl->OnPaint) {
        vtbl->OnPaint(wnd);
    }
}

bool Label_OnEvent(STWnd *wnd, STKeyEvent ev) {
    (void)wnd;
    (void)ev;
    return false;
}

// 标签创建函数
STLabel *CreateLabel()
{
    static const STWndVApi labelVtbl = {
        .OnInit = Label_OnInit,
        .OnDestroy = Label_OnDestroy,
        .OnPaint = Label_OnPaint,
        .OnEvent = Label_OnEvent};

    STLabel *label = (STLabel *)(g_wndApi.CreateWndEx(sizeof(STLabel), WND_TYPE_LABEL, &labelVtbl));
    if (label) {
        label->SetText = Label_SetText;
    }
    return label;
}
